package com.chaosyeb.server.controller;

import com.chaosyeb.server.pojo.Admin;
import com.chaosyeb.server.pojo.AdminLoginParam;
import com.chaosyeb.server.pojo.RespBean;
import com.chaosyeb.server.service.IAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * @Description : 登录
 * @Author : Chaos
 * @Date : 2021/12/4 21:40
 * @Version : 1.0
 **/
@Api(tags = "LoginController")
@RestController
@Slf4j
public class LoginController {

    @Autowired
    private IAdminService adminService;

    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request){
        System.out.println("===codetest==="+adminLoginParam.getCode());
        System.out.println("===username==="+adminLoginParam.getUsername());
        return adminService.login(adminLoginParam.getUsername(), adminLoginParam.getPassword(), adminLoginParam.getCode(),request);
    }

    @ApiOperation(value = "获取当前登录用户的信息")
    @GetMapping("/admin/info")
    public Admin getAdminInfo(Principal principal){
        // 参数principal--->security中包含用户信息
        log.info("获取用户信息");
        if (principal == null) {
            return null;
        }
        // principal获取用户名
        String username = principal.getName();
        Admin admin = adminService.getAdminByUserName(username);
        // 将密码设置为空，密码是不能返回给前端的
        admin.setPassword(null);
        // 根据用id查询角色列表并设置角色
        admin.setRoles(adminService.getRole(admin.getId()));
        return admin;
    }

    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout(){
        return RespBean.success("注销成功");
    }
}
